import type { NextApiRequest, NextApiResponse } from 'next';
import { jsonRes } from '@fastgpt/service/common/response';
import { connectToDatabase } from '@/service/mongo';
import { delFileByFileIdList, uploadFile } from '@fastgpt/service/common/file/gridfs/controller';
import { getUploadModel } from '@fastgpt/service/common/file/multer';
import { authDataset } from '@fastgpt/service/support/permission/auth/dataset';
import { FileCreateDatasetCollectionParams } from '@fastgpt/global/core/dataset/api';
import { removeFilesByPaths } from '@fastgpt/service/common/file/utils';
import { createOneCollection } from '@fastgpt/service/core/dataset/collection/controller';
import { DatasetCollectionTypeEnum } from '@fastgpt/global/core/dataset/constants';
import { BucketNameEnum } from '@fastgpt/global/common/file/constants';
import { FormatForm2ModulesProps } from '@fastgpt/global/core/app/api';
import { Code } from '@chakra-ui/react';
import formidable, { File } from 'formidable';
import { fi } from 'date-fns/locale';

/* Don't miss that! */
export const config = {
  api: {
    bodyParser: false
  }
};

/**
 * Creates the multer uploader
 */
const upload = getUploadModel({
  maxSize: 500 * 1024 * 1024
});

type ProcessedFiles = Array<[string, File]>;

export default async function handler(req: NextApiRequest, res: NextApiResponse<any>) {
  let filePaths: string[] = [];
  let fileId: string = '';
  const { datasetId } = req.query as { datasetId: string };

  console.log(33 + datasetId);

  const files = await new Promise<ProcessedFiles | undefined>((resolve, reject) => {
    const form = new formidable.IncomingForm();
    const files: ProcessedFiles = [];
    let originFile: File;
    form.on('file', function (field, file) {
      files.push([field, file]);
      originFile = file;
    });

    form.on('end', () => {
      resolve(files);
    });
    form.on('error', (err) => reject(err));
    form.parse(req, () => {});
  });

  console.log('---file---' + files);

  jsonRes(res, {
    code: 200
  });
}
